package cn.itsource.service.impl;
import cn.hutool.crypto.SecureUtil;
import cn.itsource.constants.Constants;
import cn.itsource.domain.Employee;
import cn.itsource.domain.Login;
import cn.itsource.domain.Tenant;
import cn.itsource.dto.LoginMealDto;
import cn.itsource.dto.RegisterDto;
import cn.itsource.exception.MyException;
import cn.itsource.feign.client.LoginFeign;
import cn.itsource.mapper.EmployeeMapper;
import cn.itsource.mapper.TenantMapper;
import cn.itsource.result.JSONResult;
import cn.itsource.service.ITenantService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.LinkedHashMap;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Jason
 * @since 2022-08-28
 */

@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LoginFeign loginFeign;

    @Autowired
    private TenantMapper tenantMapper;

    /**
     * @desc 机构入驻
     * @author wujiangbo
     * @date 2022/8/29 14:38
     * @param dto
     * @return cn.itsource.result.JSONResult
     */
    @Override
    public JSONResult register(RegisterDto dto){
        /**
         * 1、入参校验
         * 2、入库
         *   2.1、入system库（员工、机构）
         *   2.2、入auth库（t_login,t_login_meal）
         */
        //1、入参校验

        //数据入库到t_login表
        Login login = new Login();
        login.setUsername(dto.getUsername());
        login.setPassword(SecureUtil.md5(dto.getPassword()));
        login.setType(dto.getType());
        JSONResult res1 = loginFeign.save(login);
        if(!res1.isSuccess()){
            throw new MyException(res1.getMessage());
        }
        LinkedHashMap map = (LinkedHashMap)res1.getData();

        //保存信息到t_login_meal表
        LoginMealDto loginMealDto = new LoginMealDto();
        loginMealDto.setLoginId(Long.valueOf(map.get("id").toString()));
        loginMealDto.setMealId(dto.getMealId());
        loginMealDto.setExpireDate(DateUtils.addDays(new Date(), 7));
        JSONResult res2 = loginFeign.saveLoginMeal(loginMealDto);
        if(!res2.isSuccess()){
            throw new MyException(res2.getMessage());
        }

        //机构信息入库
        Tenant tenant = dto.getTenant();
        tenant.setRegisterTime(new Date());
        tenant.setState(0);//0待审核，1 审核通过 ， 2审核失败
        super.insert(tenant);

        Employee employee = dto.getEmployee();
        employee.setInputTime(new Date());
        employee.setState(Constants.Employee.NORMAL_STAUS);//状态：0正常，1锁定，2注销
        employee.setTenantId(tenant.getId());//所属机构ID
        employee.setLoginId(Long.valueOf(map.get("id").toString()));
        employeeMapper.insert(employee);

        //更新
        tenant.setAdminId(employee.getId());
        super.updateById(tenant);

        return JSONResult.success();
    }

    @Override
    public JSONResult getTenantInfoByUserId(Long userId) {
        Tenant tenant = tenantMapper.getTenantInfoByUserId(userId);
        return JSONResult.success(JSONObject.toJSONString(tenant));
    }
}
